import { ref, onBeforeUnmount, onMounted } from 'vue';
import { Client } from '@stomp/stompjs';
import SockJS from 'sockjs-client';

export const useStomp = () => {
    const stompClient = ref(null);
    const userSessionId = ref('');
    const isConnected = ref(false);

    const getSessionId = () => {
        return localStorage.getItem('sessionId') || '';
    };

    const connectToWebSocket = () => {
        const socket = new SockJS('/ws');
        stompClient.value = new Client({
            webSocketFactory: () => socket,
            connectHeaders: {
                'userSessionId': userSessionId.value,
            },
            onConnect: () => {
                console.log('Connected to WebSocket');
                isConnected.value = true;
                subscribeToPaymentSuccessTopic();
            },
            onStompError: (frame) => {
                console.error('Error in WebSocket connection: ', frame);
            },
        });
        stompClient.value.activate();
    };

    const subscribeToPaymentSuccessTopic = () => {
        stompClient.value.subscribe(`/user/${userSessionId.value}/topic/paymentSuccess`, (message) => {
            console.log('Payment Success Message:', message.body);
            alert(message.body);
        });
    };

    onMounted(() => {
        userSessionId.value = getSessionId();
        connectToWebSocket();
    });

    onBeforeUnmount(() => {
        if (stompClient.value) {
            stompClient.value.deactivate();
        }
    });

    return {
        stompClient,
        userSessionId,
        isConnected
    };
};